package com.mozz.finally_work.servlet.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mozz.finally_work.dao.CollectionDao;
import com.mozz.finally_work.dao.SubscribeDao;
import com.mozz.finally_work.pojo.BlogStatus;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "QueryBlogStatusServlet", value = "/QueryBlogStatusServlet")
public class QueryBlogStatusServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取参数*/
        String userId = request.getParameter("userId");
        String targetId = request.getParameter("targetId");
        String blogId = request.getParameter("blogId");
        System.out.println(userId);
        System.out.println(targetId);
        System.out.println(blogId);
        /*调用dao*/
        SqlSession session = MybatisUtils.getSession();
        CollectionDao collectionDao = session.getMapper(CollectionDao.class);
        SubscribeDao subscribeDao = session.getMapper(SubscribeDao.class);
        Integer ret1 = collectionDao.isCollection(userId, blogId);
        Integer ret2 = subscribeDao.isSubscribe(userId, targetId);
        BlogStatus blogStatus = new BlogStatus();
        blogStatus.setCollection(ret1==1);
        blogStatus.setSubscribe(ret2 == 1);
        session.close();
        /*转为json对象*/
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(blogStatus);
        System.out.println(result);
        /*响应请求*/
        response.setHeader("Content-Type", "application/json; charset=UTF-8");
        response.getWriter().write(result);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
